<!-- 用户博客页面整体框架 -->
<template>
    <div style="background-color: #f5f4f1; min-height: 190vh">
        <!-- 导航栏开始 -->
        <UserNav/>
        <!-- 导航栏结束 -->
        <!-- 主体区域 -->
        <div style="width: 1024px; position: relative; top: 100px; margin: 0 auto">
            <!-- 个人信息区域开始 -->
            <div style="background-color: #fffefb; width: 100%; display: flex; height: 150px">
                <!-- 头像 -->
                <div style="display: flex; align-items: center; justify-content: center; margin-left: 30px; margin-right: 20px">
                    <el-avatar shape="circle" :size="70" fit="cover" :src="data.user.profile_photo_path" @error="errorHandler">
                        <img
                            src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                            alt="加载错误"/> <!--图片加载失败的回退行为-->
                    </el-avatar>
                </div>
                <!-- 个人基本信息 -->
                <div style="display: flex; justify-content: center; width: 180px; flex-direction: column">
                    <h3  style="margin: 10px 0">{{data.user.username}}</h3>
                    <p  style="margin: 10px 0"><span style="margin-right: 10px"><strong style="margin-right: 5px">123</strong>关注</span>|<span style="margin-left: 10px"><strong style="margin-right: 5px">123</strong>粉丝</span></p>
                </div>
                <div style="display: flex; justify-content: center; margin-left: 50px; width: 500px;flex-direction: column">
                    <p style="margin: 7px">用户id : {{ data.user.user_id }}</p>
                    <!--<p style="margin: 7px">简介：青春八素到那个粗奥收到您的噶喀什难道就噶案例的归纳数据库的感觉阿松奥斯陆扩大国内军啊速度给</p>-->
                    <p style="margin: 7px">加入ITCACP时间：<span>{{ data.user.created_at }}</span></p>
                </div>
                <!-- 功能 -->
                <div style="display: flex; justify-content: center; align-items: center; width: 274px" v-if="isUserAuth">
                    <el-button type="primary">关注</el-button>
                    <el-button>私信</el-button>
                </div>
                <div style="display: flex; justify-content: center; align-items: center; width: 274px" v-else>
                    <router-link to="/personalcenter/personalprofile"><el-button type="primary">设置</el-button></router-link>
                </div>
            </div>
            <!-- 个人信息区域结束 -->

            <!-- 其他信息信息区域开始 -->
            <div style="width: 240px; height: 500px; background-color: #fffefb; margin-top: 20px; position: absolute; right: 0">
                <div style="display: flex; align-items: center; justify-content: center; gap: 50px">
                    <!-- 文章数 -->
                    <div>
                        <p style="text-align: center">{{allContent.length}}</p>
                        <strong style="font-weight: 500; font-size: 15px">内容数</strong>
                    </div>
                    <!-- 项目数 -->
                    <div>
                        <p style="text-align: center">{{allProject.length}}</p>
                        <strong style="font-weight: 500; font-size: 15px">项目数</strong>
                    </div>
                </div>
                <!--我的标签区域开始-->
                <div style="margin: 20px 5px">
                    <p style="margin: 4px 0">
                        兴趣标签：
                        <span v-if="data.user.tags"><el-tag v-for="tag in data.user.tags.split(',')" :key="tag" type="success" style="margin-right: 5px; margin-top: 5px">{{ tag }}</el-tag></span>
                        <span v-else>暂未选择感兴趣的标签！</span>
                    </p>
                </div>
                <!--我的标签区域结束-->
            </div>
            <!-- 其他信息区域结束 -->

            <!-- 个人内容区域开始 -->
            <div style="background-color: #fffefb; width: 760px; min-height: 120vh; position: absolute; top: 170px; left: 0">
                <div style="border-bottom: 1px rgba(204,203,200,0.50) solid; height: 60px; display: flex">
                    <!-- 内容分类按钮区 -->
                    <div style="display: flex; align-items: center; justify-content: left; margin-left: 20px">
                        <el-menu router :default-active="router.currentRoute.value.path" @select="handleMenuSelect">
                            <el-menu-item :index="`/personalhome/${userId}`">
                                <span>全部</span>
                            </el-menu-item>
                            <el-menu-item :index="`/personalhome/${userId}/BOLG`">
                                <span>博客</span>
                            </el-menu-item>
                            <el-menu-item :index="`/personalhome/${userId}/QUESTION`">
                                <span>问答</span>
                            </el-menu-item>
                            <el-menu-item :index="`/personalhome/${userId}/PROJECT`">
                                <span>项目</span>
                            </el-menu-item>
                            <el-menu-item :index="`/personalhome/${userId}/ESSAY`">
                                <span>随记</span>
                            </el-menu-item>
                        </el-menu>
                    </div>
                    <!-- 搜索区 -->
                    <div style="display: flex; align-items: center; justify-content: right; flex: 1">
                        <el-input v-model="data.content" placeholder="请输入内容以搜索" size="default" style="width: 300px"/>
                        <el-button type="primary" style="margin: 15px" @click="searchContent">搜索</el-button>
                    </div>
                </div>
                <!-- 内容展示区域 -->
                    <!-- 内容展示区 auto 开始-->
                    <!--无数据时的显示策略-->
                    <div v-if="state.isNoContentData" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center" >
                        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 280px; height: 280px">
                    </div>
                    <div v-else class="autobox-container-ar">
                        <!--博客列表开始-->
                        <div class="blog-list">
                            <!-- 卡片 -->
                            <div class="blog-item" v-for="item in data.contentList" :key="item.contentId">
                                <router-link :to="`/contentdetail/${item.contentType}/${item.contentId}`">
                                    <!-- 内容主体区域 -->
                                    <div class="blog-main-content">

                                        <div style="display: flex; align-items: center; justify-content: space-between">
                                            <!-- 标题 + 内容（左） -->
                                            <div :style="item.cover ? 'width: 550px' : 'width: 720px'" >
                                                <strong class="blog-title">{{ item.title }}</strong>
                                                <div v-if="item.contentType !== 'QUESTION'" class="blog-desc">{{ truncateText(stripHtml(item.content), 150) }}</div><!-- DOMPurify 库去除HTML标签 -->
                                            </div>
                                            <!-- 封面图片（右） -->
                                            <div class="blog-cover" v-if="item.cover">
                                                <el-image style="width: 100%; height: 100%; border-radius: 0.375rem" :src="item.cover" fit="cover" :preview-src-list="[item.cover]"/>
                                            </div>
                                        </div>
                                        <!-- 文章信息区域（预留）：置于内容底部靠左-->
                                        <div class="user-info-area">
                                            <!-- 用户信息区域 靠左 -->
                                            <el-avatar :src="item.user.profile_photo_path" shape="circle" :size="30" @error="errorHandler">
                                                <img
                                                    src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                                                    alt="加载错误"/> <!--图片加载失败的回退行为-->
                                            </el-avatar>
                                            <div class="interaction-info">
                                                <span>{{ item.user.username }}</span>
                                                <span class="icon-item"><img src="@/assets/icon_svg/浏览量.svg" alt="icon" style="width: 20px; height: 20px">{{ item.views }}</span>
                                                <span class="icon-item"><img src="@/assets/icon_svg/赞.svg" alt="点赞图标" style="width: 20px; height: 20px">{{ item.likes }}</span>
                                                <span class="icon-item"><img src="@/assets/icon_svg/_收藏.svg" alt="icon" style="width: 20px; height: 20px"> {{ item.collections }}</span>
                                            </div>
                                            <!--分类标签区域 靠右-->
                                            <div class="blog-meta">
                                                <span v-if="item.category?.categoryName" class="category-tag"><el-tag type="info">{{ item.category?.categoryName }}</el-tag></span>
                                                <span v-if="item.tags" class="tag-list"><el-tag v-for="tag in item.tags.split(',')" :key="tag" type="success">{{ tag }}</el-tag></span>
                                                <span class="publish-time">{{ item.created_at.split(' ')[0] }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </router-link>
                            </div>
                        </div>
                        <!--内容列表结束-->
                    </div>
                    <!-- 项目展示区开始 -->
                    <div v-if="route.params.type === 'PROJECT'">
                        <!-- 内容展示区 auto 开始-->
                        <!--无数据时的显示策略-->
                        <div v-if="state.isNoProjectData" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center" >
                            <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 280px; height: 280px">
                        </div>
                        <div v-else class="autobox-container-ar">
                            <!--列表开始-->
                            <div class="blog-list">
                                <!-- 卡片 -->
                                <div class="blog-item" v-for="item in data.projectList" :key="item.projectId">
                                    <!-- 内容主体区域 -->
                                    <div class="blog-main-content">
                                        <router-link :to="`/projects/${item.projectId}`">
                                            <div style="display: flex; align-items: center; justify-content: space-between">
                                                <!-- 标题 + 内容（左） -->
                                                <div style="width: 670px" >
                                                    <div style="display:flex; align-items: center">
                                                        <el-avatar :src="item.user.profile_photo_path" shape="circle" :size="30" @error="errorHandler">
                                                            <img
                                                                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                                                                alt="加载错误"/> <!--图片加载失败的回退行为-->
                                                        </el-avatar>
                                                        <strong style="font-size: 18px;font-weight: 600;color: #1f2937; margin-bottom: 8px;display: block;margin-left: 10px;">{{item.user?.username}} / {{item?.projectName}}</strong>
                                                    </div>
                                                    <div class="blog-desc" style="margin: 10px">{{ item.description }}</div><!-- DOMPurify 库去除HTML标签 -->
                                                </div>
                                                <span class="icon-item"><img src="@/assets/icon_svg/_收藏.svg" alt="icon" style="width: 20px; height: 20px; margin-right: 5px"> {{ item.collections }}</span>
                                            </div>
                                        </router-link>
                                        <!-- 文章信息区域（预留）：置于内容底部靠左-->
                                        <div class="user-info-area">
                                            <!--分类标签区域-->
                                            <div style="display: flex">
                                                <span style="display: flex"><img src="@/assets/icon_svg/浏览量.svg" alt="icon" style="width: 20px; height: 20px; margin-right: 5px">{{ item.views }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                                <span v-if="item.category"><el-tag type="info">{{ item.category?.categoryName }}</el-tag>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                                <span v-else><el-tag type="info">其他</el-tag>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                                <span v-if="item.tags" class="tag-list"><el-tag v-for="tag in item.tags.split(',')" :key="tag" type="success">{{ tag }}</el-tag></span>
                                                <span v-else><el-tag type="success">其他</el-tag></span>
                                                <span class="publish-time">&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;{{ item.createdAt }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!--列表结束-->
                        </div>
                        <!-- 项目展示区开始 -->
                    </div>
            </div>
            <!-- 个人内容区域结束 -->
        </div>
    </div>
</template>

<script setup>
import {onMounted, ref, reactive, computed} from 'vue'
import UserNav from "@/components/UserNav.vue";
import router from "@/router/index.js";
import {useRoute} from "vue-router";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import DOMPurify from "dompurify";
// 初始化加载
onMounted(() => {
    userId === user.user_id ? isUserAuth.value = false : isUserAuth.value = true // 用户判断
    loadUser()  // 加载用户信息
    loadContent() // 加载对应内容
    loadProject() // 加载对应项目
        // ...
})
const errorHandler = () => true // 图片处理失败的回退行为
// 用户验证：用于展示个人主页，还是展示其余用户博客页面
const isUserAuth = ref(false)

//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}
// 数据
const allContent = ref([]);// 用户所有内容
const allProject = ref([]);// 用户所有项目
const data = reactive({
    contentList: [],
    projectList: [],
    user: {},
    content: '',
})
// 状态管理
const state = reactive({
    isNoContentData: false,
    isNoProjectData: false,
})
// 获取路由参数中的内容ID
const route = useRoute();
const userId = route.params.userId;
const handleMenuSelect = (index) => {
    if (index === `/personalhome/${userId}`) {
        data.contentList = allContent.value; // 显示全部内容
        state.isNoContentData = data.contentList.length === 0;
    } else if (index.includes('/PROJECT')) {
        data.projectList = allProject.value; // 显示项目
        state.isNoProjectData = data.projectList.length === 0;
    } else {
        const contentType = index.split('/').pop();
        data.contentList = allContent.value.filter(item => item.contentType === contentType);
        state.isNoContentData = data.contentList.length === 0;
    }
};

// 获取userId所涉及的所有信息: 从路径中获取用户id进行对应用用户的查询
const loadUser = () => {
    request.get('/api/users/getUser', {
        params: {
            userId: userId
        }
    }).then(res => {
        if (res.code === '200') {
            data.user = res.data
            console.log(data.user)
        } else {
            ElMessage.error('获取用户信息失败')
        }
    })
}
const loadContent = () => {
    request.get('/api/content/selectContentAllByUserId', {
        params: {
            userId: userId
        }
    }).then(res => {
        if (res.code === '200') {
            allContent.value = res.data
            console.log(allContent.value)
            data.contentList = allContent.value; // 主动更新绑定的列表
            state.isNoContentData = data.contentList.length === 0;
        } else {
            ElMessage.error("获取用户内容失败")
        }
    })
}
const loadProject = () => {
    request.get('/api/projects/selectProjectAllByUserId', {
        params: {
            userId: userId
        }
    }).then(res => {
        if (res.code === '200') {
            allProject.value = res.data
            console.log(allProject.value)
            data.projectList = allProject.value; // 主动更新绑定的列表
            state.isNoProjectData = data.projectList.length === 0;
        } else {
            ElMessage.error("获取用户项目失败")
        }
    })
}
// 安全地移除HTML标签并提取纯文本
const stripHtml = (html) => {
    if (!html) return '';

    // 使用DOMPurify清理HTML，防止XSS攻击
    const clean = DOMPurify.sanitize(html);

    // 创建临时元素提取文本内容
    const temp = document.createElement('div');
    temp.innerHTML = clean;

    // 获取纯文本内容并去除多余空格
    return (temp.textContent || temp.innerText || '').trim();
};

// 截断文本并添加省略号
const truncateText = (text, length) => {
    if (text.length <= length) return text;

    // 找到最后一个完整的单词
    let truncated = text.substring(0, length);
    let lastSpace = truncated.lastIndexOf(' ');

    // 如果找到了空格，在空格处截断以避免单词被截断
    if (lastSpace !== -1) {
        truncated = truncated.substring(0, lastSpace);
    }

    return truncated + '...';
};

// 搜索
const searchContent = () => {
    request.get('/api/content/searchContent', {
        params: {
            content: data.content,
            userId: userId
        }
    }).then(res => {
        if (res.code === '200') {
            data.contentList = res.data
            state.isNoContentData = data.contentList.length === 0 // 搜索无果时的显示
        } else {
            ElMessage.error("搜索错误")
        }
    })
}
</script>

<style scoped>
/* 修改el-menu为横向排列 */
.el-menu {
    display: flex;
    border: none;
}
/* 菜单项样式 */
.el-menu-item {
    padding: 0 20px !important;
    height: 50px !important;
    line-height: 40px !important;
    border-bottom: 2px solid transparent;
    transition: all 0.2s;
    color: #4e5969 !important;
    font-size: 14px;
}
/* 鼠标悬停样式 */
.el-menu-item:hover {
    color: #1677ff !important;
    border-bottom-color: #1677ff;
    background-color: transparent !important;
}
/* 选中状态样式 */
.el-menu-item.is-active {
    color: #1677ff !important;
    border-bottom-color: #1677ff;
    font-weight: 500;
}
/* 移除默认的高亮背景 */
.el-menu-item:focus, .el-menu-item:hover {
    background-color: transparent !important;
}
/*中间内容区域容器：*/
.autobox-container-ar {
    position: absolute;
    width: 760px;
    box-sizing: border-box;
    background-color: #fffefb;
    min-height: 80vh;
}

/*卡片样式*/
.blog-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    gap: 22px;
    padding: 20px;
    border-bottom: 2px #f5f4f1 solid;
    transition: transform 0.3s, box-shadow 0.3s;
}
.blog-item:hover {
    background-color: #f5f4f1;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.10); /* 轻微外阴影 */
}
/* 用户信息区域样式 */
.user-info-area {
    width: 100%;
    display: flex;
    align-items: center;
}

/* 内容主体区域样式 */
.blog-main-content {
    display: flex;
    flex-direction: column;
}

/*标题样式*/
.blog-title {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 10px 0 20px 0;
}
/*内容样式*/
.blog-desc {
    font-size: 14px;
    line-height: 1.6;
    color: #4f4f4f;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 限制3行 */
    /*padding: 10px 0;*/
}

/* 封面图片样式 */
.blog-cover {
    flex: 0 0 180px; /* 固定宽度，不随内容缩放 */
    display: flex;
    align-items: center;
    width: 140px;
    height: 70px;
    position: absolute;
    right: 10px;
}

/*分类标签样式*/
.blog-meta {
    position: absolute;
    right: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
    color: #666;
    margin-left: 10px;
}

/*互动信息区样式*/
.interaction-info {
    display: flex;
    align-items: center;
    gap: 20px;
    font-size: 14px;
    color: #666;
    margin-left: 10px;
}
.icon-item {
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.2s;
}
/*.icon-item:hover {*/
/*    transform: scale(1.1);*/
/*}*/
.liked img {
    filter: brightness(0.8) hue-rotate(180deg); /* 点赞后图标变色 */
}
.blog-title {
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
    display: block;
}
</style>